package com.trendata.controller;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.trendata.aliyun.AliyunOSSClient;
import com.trendata.domain.Image;
import com.trendata.domain.Shop;
import com.trendata.service.ImageService;
import com.trendata.service.LikeService;
import com.trendata.service.ShopService;
import com.trendata.util.Constants;
import com.trendata.util.FileUploadUtil;
import com.trendata.util.JsonResult;
import com.trendata.util.ResultDO;
import com.trendata.util.TimeUtil;

/**
 * 处理需要登录店铺的接口
 * 
 * @author: HuangXiuXiu Email:243559392@qq.com
 */
@Controller
@RequestMapping("/shop")
public class ShopController {

	@Autowired
	private ShopService shopService;
	@Autowired
	private ImageService imageService;
	@Autowired
	private LikeService likeService;

	/**
	 * 获取登录的店铺信息
	 * <p>
	 * url=/shop/getShop.do
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getShop")
	@ResponseBody
	public String getShop(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		Shop shop = (Shop) request.getSession().getAttribute(Constants.SESSION_TYPE_SHOP);
		result.setValue(shop);
		result.setSuccess(true);
		return result.toJsonString();
	}

	/**
	 * 上传图片，可上传多张图
	 * <p>
	 * url=/shop/uploadImage.do
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/uploadImage")
	@ResponseBody
	public Object uploadImage(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		Shop shop = (Shop) request.getSession().getAttribute(Constants.SESSION_TYPE_SHOP);
		List<FileItem> fileItems = FileUploadUtil.uploadImages(request);
		Calendar calendar = Calendar.getInstance();
		ObjectMetadata objectMetadata = new ObjectMetadata();
		ResultDO<String> resultDO = null;
		List<String> imageUrls = new ArrayList<String>();
		result.setValue(imageUrls);
		for (FileItem fileItem : fileItems) {
			try {
				objectMetadata.setContentLength(fileItem.getSize());
				objectMetadata.setContentEncoding("utf-8");
				objectMetadata.setContentType(fileItem.getContentType());
				StringBuffer keyBuffer = new StringBuffer("snapshot/shops/" + shop.getOpenId() + "/publicImages/"
						+ calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/"
						+ calendar.get(Calendar.DAY_OF_MONTH) + "/" + new java.util.Date().getTime());
				String cutKey = keyBuffer.toString() + "_cut.jpg";
				keyBuffer.append(".jpg");
				// 上传图片到oss
				resultDO = AliyunOSSClient.putObject(keyBuffer.toString(), fileItem.getInputStream(), objectMetadata);
				if (resultDO.isSuccess()) {
					// 插入到数据库
					String url = resultDO.getModule();
					imageUrls.add(url);
					Image image = new Image();
					image.setUserOpenId(shop.getOpenId() + "");
					image.setShopOpenId(shop.getOpenId());
					image.setUrl(url);
					image.setState(Image.STATE_SHOW);
					image.setCreateTime(TimeUtil.getCurrent());
					imageService.insert(image);
					// 生成缩略图
					HttpURLConnection httpURLConnection = AliyunOSSClient.callImgService(keyBuffer.toString(),
							Constants.CUT_IMAGE_TRANSFORM);
					// 上传缩略图
					objectMetadata.setContentLength(httpURLConnection.getContentLengthLong());
					AliyunOSSClient.putObject(cutKey, httpURLConnection.getInputStream(), objectMetadata);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		result.setSuccess(true);
		return result.toJsonString();
	}

	/**
	 * 批量删除图片，只能删除自己上传的图片
	 * <p>
	 * url=/user/deleteImages.do?imageIds=1;2;3;4
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/deleteImages")
	@ResponseBody
	public String deleteImages(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		Shop shop = (Shop) request.getSession().getAttribute(Constants.SESSION_TYPE_SHOP);
		String imageIds = request.getParameter("imageIds");
		if (imageIds == null || imageIds.equals("")) {
			return result.setMessage("图片编号格式错误").toJsonString();
		}
		try {
			String[] imageIdArray = imageIds.split(";");
			for (String id : imageIdArray) {
				Image image = imageService.selectById(Integer.valueOf(id));
				if (image == null) {
					continue;
				}
				// 判断是不是本人的
				if (!image.getUserOpenId().equals(shop.getOpenId())) {
					continue;
				}
				String url = image.getUrl();
				// 删除oss上的图片
				url = url.substring(AliyunOSSClient.CDN_NAME.length());
				String cutUrl = url.substring(0, url.indexOf("."));
				cutUrl = cutUrl + "_cut.jpg";
				AliyunOSSClient.deleteObject(url);
				// 删除缩略图
				AliyunOSSClient.deleteObject(cutUrl);
				// 删除数据库的
				imageService.deleteById(image.getId());
				// 删除点赞
				likeService.deleteByImageId(image.getId());
			}
		} catch (Exception e) {
			return result.setMessage("删除时出现错误，请检查传入的编号格式").toJsonString();
		}

		result.setSuccess(true);
		return result.toJsonString();
	}

	// TODO 店主修改图片状态
	/**
	 * 修改图片状态
	 * <p>
	 * url=/shop/updateShopImage.do?state=&imageIds=1;2;3
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/updateShopImage")
	@ResponseBody
	public String updateShopImage(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		Shop shop = (Shop) request.getSession().getAttribute(Constants.SESSION_TYPE_SHOP);
		String imageIds = request.getParameter("imageIds");
		String state = request.getParameter("state");
		if (imageIds == null || imageIds.equals("") || state == null || state.equals(Image.STATE_PRIVATE)) {
			return result.setMessage("参数错误").toJsonString();
		}
		try {
			String[] imageIdArray = imageIds.split(";");
			for (String id : imageIdArray) {
				Image image = imageService.selectById(Integer.valueOf(id));
				// 是店主的店的，修改状态
				if (image != null && image.getShopOpenId() == shop.getOpenId()) {
					image.setState(Integer.valueOf(state));
					imageService.update(image);
				}
			}
		} catch (Exception e) {
			return result.setMessage("删除时出现错误，请检查传入的编号格式").toJsonString();
		}
		result.setSuccess(true);
		return result.toJsonString();
	}

}
